<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <div
        style="overflow: hidden"
        :style="{
          height: openShow ? 'auto' : '80px',
        }"
      >
        <el-form
          id="searchForm"
          :model="formData"
          label-position="top"
          style="display: flex; flex-wrap: wrap; height: auto"
          @submit.native.prevent
        >
          <el-form-item
            style="margin-right: 20px"
            :label="item.name"
            v-for="(item, index) in chooseFilterField"
            :key="index"
            :prop="item.field"
          >
            <input-type
              :filterModule="true"
              :propData="item"
              :searchShow="true"
              :propValue="formData[item.field]"
              @updatePropValue="updatePropValue"
              @querySearch="handleSearchFunc"
            ></input-type>
            <template v-if="item.type === 'number-range'">
              <template slot="label">
                <span>{{ item.name }}</span>
                <el-tooltip content="区间最小值和最大值必填" placement="top">
                  <i
                    style="
                      font-size: 12px;
                      color: #b3b9c7;
                      margin-left: 6px;
                      cursor: pointer;
                    "
                    class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
                  ></i>
                </el-tooltip>
              </template>
              <el-input-number
                v-model="formData[item.field][0]"
                :controls="false"
                size="small"
                :precision="0"
                :min="0"
                :max="formData[item.field][1]"
                @blur="handleSearchFunc"
              />
              <span style="margin: 0 6px">-</span>
              <el-input-number
                v-model="formData[item.field][1]"
                :controls="false"
                size="small"
                :precision="0"
                :min="formData[item.field][0] ? formData[item.field][0] : 0"
                @blur="handleSearchFunc"
              />
            </template>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template slot="oprate">
      <div v-if="searchHeight > 100" @click="handleLines" class="open">
        <i :class="openShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />{{
          openShow ? "收起" : "展开"
        }}
      </div>
      <customFilter
        name="自定义"
        :chooseData="chooseFilterField"
        :getCusAllFields="searchFields"
        @saveFilter="saveFilter"
      >
        <div slot="tip" class="tip-content">请务必选择一个时间条件</div>
      </customFilter>
      <advancedSearch
        ref="customSearch"
        class="customSearch"
        :fieldList="advanceFields"
        :fieldSelectList="fieldSelectList"
        :conditionList="conditionList"
        :customList="customList"
        :searchType="searchType"
        @deleteCustomClick="deleteCustomClick"
        @saveCondition="saveConditionFun"
        @handleSearch="handleSearch"
      ></advancedSearch>
      <el-button type="primary" size="mini" @click="handleSearchFunc"
        >查询</el-button
      >
    </template>
    <template slot="content">
      <configTable
        v-if="isShowTabel"
        :headers="tableHeaders"
        ref="smsTable"
        :data="tableData"
        :pagingData="pagingData"
        :batchs="batchs"
        :selection="true"
        :headersConfig="true"
        @batchClick="batchClick"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.show && !['type', 'sendResult'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :min-width="item.width"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
            </u-table-column>
            <u-table-column
              v-if="item.show && ['type'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :min-width="item.width"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">
                <span>{{ row.type | filterSmsType }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && ['sendResult'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :min-width="item.width"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">
                <span>{{ row.sendResult | filtersendResult }}</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import { commonAction, deepClone, getFormatDateTime, isHasFuncOrMenus } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import inputType from '@/views/newCustomer/common/inputType.vue'
import customFilter from '@/components/customFilter/index.vue'
import advancedSearch from '@/views/newCustomer/common/advanceSearch/advancedSearch.vue'
import { v4 as uuidv4 } from 'uuid'
@Component({
  name: 'smsRecord',
  components: {
    configTable,
    continer,
    inputType,
    customFilter,
    advancedSearch
  },
  filters: {
    filterSmsType (type: any) {
      switch (type) {
        case 'validateCode':
          return '验证码'
        case 'notice':
          return '通知短信'
        case 'marketing':
          return '营销短信'
      }
    },
    filtersendResult (res: any) {
      switch (res) {
        case 1:
          return '发送中'
        case 2:
          return '重试中'
        case 3:
          return '发送成功'
        case 4:
          return '发送失败'
      }
    }
  }
})
export default class ResultQuery extends Vue {
  [x: string]: any
  private batchs: any = [
    {
      name: '批量导出',
      action: 'export',
      _id: 'sms_record_batch_export'
    }
  ]

  private openShow: boolean = false

  private chooseFilterField: any = []

  private searchHeight: any = 0

  private advanceQuery: any = [] // 高级搜索

  private formData: any = {
    splitNumber: [],
    submitTime: [],
    receiveReceiptTime: []
  }

  private isShowTabel: boolean = false

  private tableData: any = []

  private pagingData = { total: 0, limit: 10, page: 1 }

  private checkHeaders: any = []

  private tableHeaders: object[] = []

  private searchType: any = 'custom' // custom自定义 advance高级

  private searchFields: any = [ // 自定义搜索
    { name: '短信ID', field: 'id', type: 'text' },
    { name: '手机号码', field: 'phone', type: 'text' },
    { name: '发送时间', field: 'submitTime', type: 'datetime-range' },
    { name: '发送结果', field: 'sendResult', type: 'dropdown' },
    { name: '送达时间', field: 'receiveReceiptTime', type: 'datetime-range' },
    { name: '拆分条数', field: 'splitNumber', type: 'number-range' },
    { name: '通道失败原因', field: 'channelFailReason', type: 'text' },
    { name: '发送失败原因', field: 'failReason', type: 'text' },
    { name: '签名ID', field: 'signId', type: 'text' },
    { name: '签名', field: 'sign', type: 'text' },
    { name: '模板ID', field: 'templateId', type: 'text' },
    { name: '短信类型', field: 'type', type: 'dropdown' },
    { name: '短信内容', field: 'content', type: 'text' }
  ]

  private advanceFields: any = [
    { label: '短信ID', prop: 'id' },
    { label: '手机号码', prop: 'phone' },
    { label: '发送时间', prop: 'submitTime' },
    { label: '发送结果', prop: 'sendResult' },
    { label: '送达时间', prop: 'receiveReceiptTime' },
    { label: '拆分条数', prop: 'splitNumber' },
    { label: '通道失败原因', prop: 'channelFailReason' },
    { label: '发送失败原因', prop: 'failReason' },
    { label: '签名ID', prop: 'signId' },
    { label: '签名', prop: 'sign' },
    { label: '模板ID', prop: 'templateId' },
    { label: '短信类型', prop: 'type' },
    { label: '短信内容', prop: 'content' }
  ]

  private sendResult: any = [
    {
      value: '发送中',
      key: 1
    },
    {
      value: '重试中',
      key: 2
    },
    {
      value: '发送成功',
      key: 3
    },
    {
      value: '发送失败',
      key: 4
    }
  ]

  private smsType: any = [
    {
      value: '验证码',
      key: 'validateCode'
    },
    {
      value: '营销短信',
      key: 'marketing'
    },
    {
      value: '通知短信',
      key: 'notice'
    }
  ]

  get getRegionList () {
    return this.$store.state.common.publicCache.region.result || []
  }

  get getUserList () {
    return (CommonModule as any).publicCache.userList.map(v => ({ value: `${v.agentName} 【${v.agentNumber}】`, key: v._id }))
  }

  get getAccountId () {
    return (CommonModule as any).session.user.accountId || ''
  }

  get getUserId () {
    return (CommonModule as any).session.user._id || ''
  }

  private batchClick (action: string, selectList: any) {
    switch (action) {
      case 'export':
        this.batchExport()
        break
    }
  }

  private batchExport () {
    this.$confirm('确定要批量导出短信记录吗', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const params = {
        url: '/sms-api/sms/api/sms/task-create',
        method: 'POST',
        data: {
          requestId: this.getUUID(),
          action: 'API_SMS_EXPORT_RECORD_TASK_CREATE',
          param: {
            account: this.getAccountId,
            createUser: this.getUserId,
            ...this.formData
          }
        }
      }
      commonAction(params).then(res => {
        if (res.code === '0000200') {
          this.clearBatchSelect()
          const h = this.$createElement;
          (this.$message as any)({
            message: h('div', { style: 'color:#2ed47a' }, [
              h('span', {}, '导出成功，请前往'),
              h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
              h('span', {}, '查看')
            ]),
            type: 'success',
            duration: 5000
          })
        }
      })
    })
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    this.$router.push('/transmission_center/index/tx_export_task?taskModule=sms')
  }

  public clearBatchSelect () {
    (this as any).$refs.smsTable.cancelSelectFun()
  }

  private checkHeadersChange (checkList: any, isInit: any) {
    this.$set(this, 'checkHeaders', checkList)
    if (!isInit) {
      this.saveTabelHeaders(checkList)
    }
  }

  private saveTabelHeaders (headers: any) { // 自定义表头保存
    const data = {
      url: '/base/action/header',
      method: 'POST',
      data: {
        type: 'sms',
        config: headers
      }
    }
    commonAction(data)
  }

  private getAgentName (agentId) {
    const agent = (CommonModule as any).publicCache.userListObj[agentId]
    if (agent) {
      return agent.name
    }
    return '--'
  }

  private handleSearchFunc (type = '') { // 点击查询搜索类型变更为自定义搜索
    this.searchType = 'custom'
    this.pagingData.page = 1
    if (type === 'advance') {
      this.getData('advance')
    } else {
      this.getData()
    }
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    if (this.searchType === 'custom') { // 不同搜索类型搜索条件不同
      this.handleSearchFunc()
    } else {
      this.handleSearchFunc('advance')
    }
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    if (this.searchType === 'custom') { // 不同搜索类型搜索条件不同
      this.getData()
    } else {
      this.getData('advance')
    }
  }

  private getUUID () {
    return uuidv4().replace(/-/g, '')
  }

  private async getData (source = '') {
    let param: any = {}
    if (source === 'advance') { // 高级搜索
      this.searchType = 'advance'
      param = { account: this.getAccountId }
      if (this.advanceQuery && this.advanceQuery.length > 0) {
        param.customizationQuery = {}
        param.customizationQuery.list = this.advanceQuery
      } else {
        delete param.customizationQuery
      }
    } else { // 自定义搜索
      this.searchType = 'custom'
      const cloneForm = deepClone(this.formData)
      if (cloneForm.submitTime.length || cloneForm.receiveReceiptTime.length) {
        if ((!cloneForm.splitNumber[0] && cloneForm.splitNumber[0] !== 0) || (!cloneForm.splitNumber[1] && cloneForm.splitNumber[1] !== 0)) {
          cloneForm.splitNumber = []
        }
        param = { ...cloneForm, account: this.getAccountId }
      } else {
        return this.$message.error('自定义搜索中必须存在时间条件且至少一个时间条件需有值')
      }
    }
    const sendData = {
      action: 'API_SMS_QUERY',
      requestId: this.getUUID(),
      page: this.pagingData.page,
      pageSize: this.pagingData.limit,
      param
    }
    const res: any = await commonAction({ url: '/sms-api/sms/api/sms/query-v1', method: 'POST', data: sendData })
    if (res.code === '0000200' && res.data) {
      this.tableData = res.data.list || []
      this.pagingData.total = res.data.total || 0
    }
  }

  private handleLines () {
    this.openShow = !this.openShow
  }

  private updatePropValue (val: any, field: any) {
    this.$set(this.formData, field, val)
  }

  private saveFilter (data: any) {
    if (!data.fields.some(item => item.field === 'submitTime' || item.field === 'receiveReceiptTime')) {
      return this.$message.error('保存失败，自定义搜索中需至少存在一个时间条件')
    }
    this.formData = { // 清空数据
      splitNumber: [],
      submitTime: [],
      receiveReceiptTime: []
    }
    const params = {
      url: '/base/action/quicksearch/fields',
      method: 'POST',
      data: {
        module: 'sms',
        fields: data.fields
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        this.$message.success('保存成功')
        this.updateFilter(data.fields)
      }
    })
  }

  private updateFilter (chooseData: any) {
    chooseData.forEach(item => {
      this.getNewChoices(item)
      if (['submitTime', 'receiveReceiptTime'].includes(item.field)) { // 时间条件默认最近一周
        this.formData[item.field] = [getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 6), '').split(' ')[0] + ' 00:00:00', getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59']
      }
    })
    this.$set(this, 'chooseFilterField', chooseData)
    this.getData()
    this.$nextTick(() => {
      this.searchHeight = document.getElementById('searchForm')?.offsetHeight
    })
  }

  private getNewChoices (item: any) {
    switch (item.field) {
      case 'type':
        this.$set(item, 'choices', this.smsType)
        break
      case 'sendResult':
        this.$set(item, 'choices', this.sendResult)
        break
    }
  }

  private getFilterConf () { // 获取自定义搜索
    const params = {
      url: '/base/action/quicksearch',
      method: 'GET',
      data: {
        module: 'sms'
      }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        this.updateFilter(res.data.fields)
        this.customList = res.data.queries || []
      }
    })
  }

  // 高级搜索相关
  private conditionList: any = {
    id: { type: 'string', condition: ['eq'] },
    phone: { type: 'string', condition: ['eq'] },
    submitTime: { type: 'date', condition: ['between', 'gte', 'lte'] },
    sendResult: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    receiveReceiptTime: { type: 'date', condition: ['between', 'gte', 'lte'] },
    splitNumber: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
    channelFailReason: { type: 'string', condition: ['eq'] },
    failReason: { type: 'string', condition: ['eq'] },
    signId: { type: 'string', condition: ['eq'] },
    sign: { type: 'string', condition: ['eq'] },
    templateId: { type: 'string', condition: ['eq'] },
    type: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    content: { type: 'string', condition: ['eq'] }
  }

  private fieldSelectList: any = {
    type: [
      {
        name: '验证码',
        _id: 'validateCode'
      },
      {
        name: '营销短信',
        _id: 'marketing'
      },
      {
        name: '通知短信',
        _id: 'notice'
      }
    ],
    sendResult: [
      {
        name: '发送中',
        _id: 1
      },
      {
        name: '重试中',
        _id: 2
      },
      {
        name: '发送成功',
        _id: 3
      },
      {
        name: '发送失败',
        _id: 4
      }
    ]
  }

  private customList: any = []

  private handleSearch (advanceQuery) {
    this.pagingData.page = 1
    this.advanceQuery = advanceQuery;
    (this.$refs as any).customSearch.hide()
    this.getData('advance')
  }

  private saveConditionFun (obj: any) {
    const params = {
      url: '/base/action/quicksearch/queries',
      method: 'POST',
      data: {
        module: 'sms',
        name: obj.name,
        advanceQuery: obj.advanceQuery
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        this.getFilterConf()
      }
    })
  }

  private deleteCustomClick (item) {
    const queryObj: any = { module: 'sms', _id: item._id }
    const data = { url: '/base/action/quicksearch/queries/delete ', method: 'POST', data: queryObj }
    commonAction(data).then((res: any) => {
      if (res.success) {
        this.getFilterConf()
      }
    })
  }

  private getTabelHeaders () { // 获取自定义表头
    this.isShowTabel = false
    const params = { url: '/base/action/header', method: 'GET', data: { type: 'sms' } }
    commonAction(params).then((res: any) => {
      if (res.success && res.data && res.data.config && res.data.config.length) {
        this.$set(this, 'tableHeaders', res.data.config)
      }
      this.$nextTick(() => {
        this.isShowTabel = true
      })
    })
  }

  private mounted () {
    this.getTabelHeaders()
    this.$getCache('/base/action/general/cache/query', ['region'], false)
    this.getFilterConf()
    this.batchs = this.batchs.filter(item => isHasFuncOrMenus(item._id, this.$store.state.common.session.user, false)) // 批量操作权限过滤
  }
}
</script>
<style lang="stylus" scoped>
.tip-content
  font-size 12px
  color #999
  margin-bottom 10px
.customSearch
  margin-right 10px
>>> .drawer-contain
  padding 0 !important
  overflow hidden !important
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
>>> .el-form-item__label
  line-height 1
>>> .el-form-item__content
  display flex
  align-items center
>>> .oprate
  margin-top 20px
.open
  width 70px
  height 32px
  display flex
  align-items center
  justify-content center
  font-size 12px
  color #303854
  border 1px solid #E7E9ED
  border-radius 4px
  margin-right 10px
  cursor pointer
  i
    margin-right 5px
</style>
